package com.juneng.utils;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.juneng.utils.abnormal.CodeMsg;
import com.juneng.utils.abnormal.GlobalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@SuppressWarnings("deprecation")
public class OSSClientUtil {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /*
     * 滨海工会配置
     */
    private String endpoint = "oss-cn-hangzhou.aliyuncs.com";
    private String accessKeyId = "LTAI5tFtv1eDwpsDWPyx2YKe";
    private String accessKeySecret = "mEk8BJc1hUtjyIVty38pEA7l3xL4IX";
    private String bucketName = "liulujiayun";


    private String imageDir = "picture/";
    private String vedioDir = "vedio/";

    private OSSClient ossClient;


    public OSSClientUtil() {
        //注意： 专有云、专有域环境必须要使用ClientConfiguration的对象传入参数，不然会报错。
		//创建ClientConfiguration实例，按照您的需要修改默认参数。
		ClientConfiguration conf = new ClientConfiguration();
		//关闭CNAME选项。
		conf.setSupportCname(false);
		ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret, conf);
	}

	//初始化
	public void init() {
		ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
	}

	//销毁
	public void destory() {
		ossClient.shutdown();
	}

	/**
	 * 文件种类
	 * @param file
	 * @return
	 */
	public Integer getType(MultipartFile file) {
		String fileName = file.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
		logger.info(suffix);
		if(suffix.equals("bmp")||suffix.equals("png")||suffix.equals("gif")||suffix.equals("jpeg")||suffix.equals("jpg")) {
			return 1;
		}else if(suffix.equals("mov")||suffix.equals("mp4")||suffix.equals("avi")) {
			return 2;
		}else {
			return 0;
		}
	}

	/**
	 * 上传图片
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public String uploadImg2Oss(MultipartFile file){
		if (file.getSize() > 10 * 1024 * 1024) {
			throw new GlobalException(CodeMsg.IMAGE_SIZE_OUT);
		}
		String originalFilename = file.getOriginalFilename();
		String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
		String fileName = randomFileName(suffix);
		try {
			InputStream inputStream = file.getInputStream();
			this.uploadFile2OSS(inputStream, fileName, imageDir);
			return imageDir+fileName;
		} catch (Exception e) {
			throw new GlobalException(CodeMsg.UPLOAD_IMAGE_FAIL);
		}
	}


	/**
	 * 上传视频
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public String uploadVedio2Oss(MultipartFile file){
		if (file.getSize() > 50 * 1024 * 1024) {
			throw new GlobalException(CodeMsg.VEDIO_SIZE_OUT);
		}
		String originalFilename = file.getOriginalFilename();
		String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
		String fileName = randomFileName(suffix);
		try {
			InputStream inputStream = file.getInputStream();
			this.uploadFile2OSS(inputStream, fileName, vedioDir);
			return vedioDir+fileName;
		} catch (Exception e) {
			throw new GlobalException(CodeMsg.UPLOAD_VEDIO_FAIL);
		}
	}


    /**
     * 获得外部访问的URL链接 
     * <p>
     * Exception in thread "main" com.education.result.abnormal.GlobalException: 500904/上传图片至OSS服务器失败
     *
     * @param key
     * @return
     */
	public String getUrl(String key) {
        // 设置URL过期时间为20年 3600l* 1000*24*365*20  
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 20);
        // 生成URL  
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
//        StringBuffer sb = new StringBuffer();
//
//        sb.append("http://").append(bucketName).append(".").append(endpoint).append("/").append(key);
//        String url = sb.toString();
//        System.out.println(url);
//		return url;
    }




//内部工具方法
	/**
	* 上传到OSS服务器 如果同名文件会覆盖服务器上的
	*
	* @param instream
	*            文件流
	* @param fileName
	*            文件名称 包括后缀名
	* @return 出错返回"" ,唯一MD5数字签名
	*/
	private String uploadFile2OSS(InputStream instream, String fileName, String filedir) {
		String ret = "";
		try {
			// 创建上传Object的Metadata
			ObjectMetadata objectMetadata = new ObjectMetadata();
			objectMetadata.setContentLength(instream.available());
			objectMetadata.setCacheControl("no-cache");
			objectMetadata.setHeader("Pragma", "no-cache");
			objectMetadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf(".")+1)));
			objectMetadata.setContentDisposition("inline;filename=" + fileName);
			//System.out.println("开始上传文件");
			// 上传文件
			PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
			//PutObjectResult putResult = ossClient.putObject(bucketName,  fileName, instream, objectMetadata);
			//System.out.println("上传成功");
			ret = putResult.getETag();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (instream != null) {
					instream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}

	/**
	* 判断OSS服务文件上传时文件的contentType 
	*
	* @param filenameExtension 文件后缀
	* @return String
	*/
	private static String getContentType(String filenameExtension) {
		if (filenameExtension.equalsIgnoreCase("bmp")) {
			return "image/bmp";
		}
		if (filenameExtension.equalsIgnoreCase("gif")) {
			return "image/gif";
		}
		if (filenameExtension.equalsIgnoreCase("jpeg") || filenameExtension.equalsIgnoreCase("jpg")
			|| filenameExtension.equalsIgnoreCase("png")) {
			return "image/jpeg";
		}
		if (filenameExtension.equalsIgnoreCase("html")) {
			return "text/html";
		}
		if (filenameExtension.equalsIgnoreCase("txt")) {
			return "text/plain";
		}
		if (filenameExtension.equalsIgnoreCase("vsd")) {
			return "application/vnd.visio";
		}
		if (filenameExtension.equalsIgnoreCase("pptx") || filenameExtension.equalsIgnoreCase("ppt")) {
			return "application/vnd.ms-powerpoint";
		}
		if (filenameExtension.equalsIgnoreCase("docx") || filenameExtension.equalsIgnoreCase("doc")) {
			return "application/msword";
		}
		if (filenameExtension.equalsIgnoreCase("xml")) {
			return "text/xml";
		}
		if (filenameExtension.equalsIgnoreCase("mov")) {
			return "video/quicktime";
		}
		if (filenameExtension.equalsIgnoreCase("mp4")) {
			return "video/mp4";
		}
		if (filenameExtension.equalsIgnoreCase("avi")) {
			return "video/x-msvideo";
		}
		return "image/jpeg";
	}


	/**
	 * 生成随机文件名
	 * @param suffix
	 * @return
	 */
	public static String randomFileName(String suffix) {
		String uuid = UUID.randomUUID().toString();
		String filePath = uuid+suffix;
		return filePath;
	}


	/**
	 * 上传图片 - URL版
	 * @param url
	 * @throws Exception
	 */
    public String uploadImg2Oss(String url) {
        File fileOnServer = new File(url);
        try (FileInputStream fin = new FileInputStream(fileOnServer);) {
            String fileName = randomFileName(".jpg");
            this.uploadFile2OSS(fin, fileName, imageDir);
            return imageDir + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException(CodeMsg.UPLOAD_IMAGE_FAIL);
        }
    }

    /**
     * 获取图片路径
     *
     * @param fileUrl
     * @return
     */
    public String getImgUrl(String fileUrl) {
        if (!StringUtils.isEmpty(fileUrl)) {
            String[] split = fileUrl.split("/");
            String url = this.getUrl(this.imageDir + split[split.length - 1]);
            return url;
        }
        return null;
    }

    public static void main(String[] args) {
        //icon
        OSSClientUtil util = new OSSClientUtil();
        String ossurl = util.uploadImg2Oss("/Users/mac/Downloads/test/test20.png");
        String url = util.getUrl(ossurl);
        System.out.println(url);
        util.getImgUrl(ossurl);
        System.out.println(ossurl);
    }


}



